package site.lanmushan.framework.mapper.provider;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import site.lanmushan.framework.mapper.util.SlashSqlHelper;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.EntityTable;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Set;

/**
 * @author Administrator
 */
@Slf4j
public class SelectAllListProvider extends MapperTemplate {
    public SelectAllListProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String selectAllList(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append("select ");
        sql.append(SlashSqlHelper.createSqlColumns(entityClass));
        this.setResultType(ms, entityClass);
        EntityTable entityTable = EntityHelper.getEntityTable(entityClass);
        sql.append(SlashSqlHelper.createSqlFrom(entityTable.getName()));
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        EntityHelper.getEntityTable(entityClass);
        if (columnList.size() == 1) {
            sql.append("<where>");
            sql.append("${@site.lanmushan.framework.mapper.util.QueryWrapperUtil@createWhereString(query)}");
            sql.append("</where>");
            return sql.toString();
        } else {
            throw new MapperException("继承 deleteByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
    }

}
